package com.ethannhu.todaynews.component.content

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.drake.channel.receiveEvent
import com.ethannhu.repository.DefaultNetworkRepository
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.component.articledetail.ArticleDetailActivity
import com.ethannhu.todaynews.component.publish.ContentChangedEvent
import com.ethannhu.todaynews.databinding.FragmentContentBinding
import com.ethannhu.todaynews.fragment.BaseViewModelFragment
import com.ethannhu.todaynews.util.Constant
import com.ethannhu.todaynews.util.ImageUtil
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.collect.Lists
import com.wanglu.photoviewerlibrary.PhotoViewer
import kotlinx.coroutines.launch
import org.apache.commons.lang3.StringUtils


/**
 * 发现内容 Fragment
 */
class ContentFragment : BaseViewModelFragment<FragmentContentBinding>() {
    private lateinit var viewModel: ContentViewModel
    private lateinit var adapter: ContentAdapter
    private var isFirstShow = true

    override fun initViews() {
        super.initViews()
        binding.list.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            val decoration = DividerItemDecoration(requireActivity(), LinearLayoutManager.VERTICAL)
            addItemDecoration(decoration)
        }
    }

    override fun initData() {
        super.initData()
        //内容VM的工厂类 ，因为默认创建 VM 会使用无参构造器，如果VM添加参数则需要这个类
        val contentViewModelFactory =
            ContentViewModelFactory(requireArguments().getString(Constant.ID))
        viewModel = ViewModelProvider(this, contentViewModelFactory)[ContentViewModel::class.java]

        //本地错误提示
        initViewModel(viewModel)

        //适配器
        adapter = ContentAdapter(viewModel)
        binding.list.adapter = adapter

        lifecycleScope.launch {
            viewModel.data.collect {  //观察 viewmodel 的数据变化
                //数据处理
                if (StringUtils.isBlank(viewModel.lastId)) {
                    adapter.submitList(it.data)
                } else {
                    it.data?.let { data ->
                        adapter.addAll(data)
                    }
                }

                processRefreshAndLoadMoreStatus(true, it.data?.isEmpty() ?: true)

            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // 在组件处于 STARTED 状态时才会执行协程任务
                viewModel.toArticleDetail.collect { id ->
                    val intent = Intent(requireContext(), ArticleDetailActivity::class.java)
                    intent.putExtra(Constant.ID, id)
                    startActivity(intent)
                }
            }
        }

        // 发布后重新刷新
        receiveEvent<ContentChangedEvent> {
            viewModel.loadMore()
        }

        lifecycleScope.launch {
            viewModel.previewMedia.collect {//观察 viewmodel 的数据变化
                previewMedias(it)
            }
        }

    }

    private fun processRefreshAndLoadMoreStatus(success: Boolean, noMore: Boolean = false) {
        // 传入false表示刷新失败
        binding.refresh.finishRefresh(500, success, false) //刷新完成之后,刷新一直有新数据，所以为 false
        //next=nULL，表示没有更多数据了
        binding.refresh.finishLoadMore(500, success, noMore) //加载更多完成之后
    }

    override fun onError() {
        super.onError()
        processRefreshAndLoadMoreStatus(false)
    }

    override fun initListeners() {
        super.initListeners()
        //下拉刷新监听器
        binding.refresh.setOnRefreshListener {
            viewModel.loadMore()
        }
        //上拉加载更多
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadMore(adapter.items.lastOrNull()?.id)  //指的是 adapter 中 item的id，item 是 content类型的
        }
    }

    override fun onResume() {
        super.onResume()
        // 懒加载
        // 每次切换标签都会创建 Fragment 的示例
        if (isFirstShow) {
            //viewModel.loadMore();
            binding.refresh.autoRefresh()  //调用刷新监听器自动刷新
            isFirstShow = false
        }

    }

    private fun previewMedias(data: PreviewMediaPageData) {
        //将List转为ArrayList
        //因为图片框架需要的是ArrayList
        val medias = Lists.newArrayList<String>(data.medias)
        PhotoViewer.setData(medias)
            //设置当前位置
            .setCurrentPage(data.position)
            //他需要容器的目的是显示缩放动画
            .setImgContainer(data.view)
            //设置图片加载回调
            .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                override fun show(iv: ImageView, url: String) {
                    ImageUtil.show(
                        iv,
                        url
                    )
                }
            })//启动界面
            .start(this)
    }


    companion object {
        const val TAG = "ContentFragment"
        fun newInstance(categoryId: String? = null) =
            ContentFragment().apply {
                categoryId?.let {
                    arguments = Bundle().apply {
                        putString(Constant.ID, it)
                    }
                }
            }
    }
}